/**
 * Project:mail-settings-detector
 * File:PortUtils.java
 * Copyright 2004-2014 Homolo Co., Ltd. All rights reserved.
 */
package com.homolo.msd.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.Socket;

/**
 * The system port utility.
 *
 * @author rory
 */
public final class PortUtils {

    /**
     * The slf4j logger.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(PortUtils.class);

    /**
     * The default private constructor.
     */
    private PortUtils() {
    }

    /**
     * check the port open or not.
     *
     * @param host the host to check
     * @param port the port to check
     * @return true if the port on the host is open
     */
    public static boolean isOpen(String host, int port) {
        Socket socket = null;
        try {
            socket = new Socket(host, port);
            socket.setSoTimeout(3000);
            socket.setReuseAddress(true);
            return true;
        } catch (IOException e) {
            LOGGER.debug("check the host:{} port:{} open or not error:{}", host, port, e);
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    /* should not be thrown */
                    LOGGER.info("never mined", e);
                }
            }
        }
        return false;
    }
}
